package utils

import (
	"encoding/base64"
	"errors"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)

func ProcessTemplates(path string) *template.Template {
	funcMap := template.FuncMap{
		"idToString":       IdToString,
		"sliceToString":    SliceToString,
		"defaultToVal":     DefaultToVal,
		"dateTimeToString": DatetimeToString,
	}

	templates := template.Must(template.New("").Funcs(funcMap).ParseGlob(path))

	return templates
}

func SetSiteEnvs() (string, string) {
	siteName, nameOk := os.LookupEnv("SITE_NAME")
	siteTitle, titleOk := os.LookupEnv("SITE_TITLE")
	if !nameOk || siteName == "" {
		siteName = "Welcome to IMABON!"
	}
	if !titleOk || siteTitle == "" {
		siteTitle = "IMABON"
	}
	return siteName, siteTitle
}

func ProcessRequestImage(req *http.Request) (string, error) {
	req.ParseMultipartForm(32 << 20)
	var imgBase64Str string
	file, _, err := req.FormFile("image")

	if err != nil {
		log.Printf("Error occurred when processing image: %s\n", err)
		return imgBase64Str, err
	}
	defer file.Close()

	fileData, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Println(err)
		return imgBase64Str, err
	}

	contentType := http.DetectContentType(fileData)
	if contentType != "image/png" &&
		contentType != "image/jpeg" &&
		contentType != "image/gif" &&
		contentType != "image/webp" {
		msg := "Type not supported yet: " + contentType
		log.Println(msg)
		return imgBase64Str, errors.New(msg)
	}

	imgBase64Str = base64.StdEncoding.EncodeToString(fileData)
	return imgBase64Str, nil
}
